package org.loofer.ext.component.drawable;

import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;

public class MatrixDrawable extends DrawableDecorator {
    private final Matrix mMatrix;
    private final MatrixState mState;

    static class MatrixState extends DrawableDecoratorState {
        MatrixState(DrawableDecoratorState orig, DrawableDecorator owner, Resources res) {
            super(orig, owner, res);
        }

        public Drawable newDrawable() {
            return new MatrixDrawable(this, null);
        }

        public Drawable newDrawable(Resources res) {
            return new MatrixDrawable(this, res);
        }
    }

    public MatrixDrawable(Drawable drawable) {
        this(drawable, null);
    }

    public MatrixDrawable(Drawable drawable, Matrix matrix) {
        this.mMatrix = new Matrix();
        this.mState = new MatrixState(null, this, null);
        this.mState.setDrawable(drawable);
        setConstantState(this.mState);
        setMatrix(matrix);
    }

    public Matrix getMatrix() {
        return this.mMatrix;
    }

    public void setMatrix(Matrix matrix) {
        if (matrix != null && matrix.isIdentity()) {
            matrix = null;
        }
        if ((matrix == null && !this.mMatrix.isIdentity()) || (matrix != null && !this.mMatrix.equals(matrix))) {
            this.mMatrix.set(matrix);
            invalidateSelf();
        }
    }

    public void draw(Canvas canvas) {
        if (this.mMatrix.isIdentity()) {
            super.draw(canvas);
            return;
        }
        int saveCount = canvas.getSaveCount();
        canvas.save();
        canvas.concat(this.mMatrix);
        super.draw(canvas);
        canvas.restoreToCount(saveCount);
    }

    private MatrixDrawable(MatrixState state, Resources res) {
        this.mMatrix = new Matrix();
        this.mState = new MatrixState(state, this, res);
        setConstantState(this.mState);
    }
}
